//
//  HRAppDelegate.m
//  haierapp
//
//  Created by zhang on 14-8-5.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRAppDelegate.h"
#import "HRInterfaceManager.h"
#import "HRPaymentManager.h"

#import "AlixPayResult.h"
#import "DataVerifier.h"


@implementation HRAppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    //上传APP启动耗时
    double end=[[NSDate date]timeIntervalSince1970];
    
    double duration=end - [HRCommonData shareCommonData].appStartTime;
    
    duration = duration*1000;//以毫秒为单位
    
    
    //启动信息日志
    
    NSString *sdkVersion = @"1.0";
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    //[uAnalysisManager onAppStartEvent:sdkVersion withAppVsersion:appVersion];
    
    //启动耗时[海尔检测平台]
    //[uAnalysisManager onAppLoadOverEvent:duration];
    
    //APP异常崩溃日志
    [HRCrashExceptionCatcher startCrashExceptionCatch];
    
    //获取保存的登录用户数据
    [[HRCommonData shareCommonData] getLoginUserFromDefaults];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [[HRCommonData shareCommonData] setDataHasNew];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
             // Replace this implementation with code to handle the error appropriately.
             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

#pragma mark - Alipay Methods

//独立客户端回调函数
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
	
	[self parse:url application:application];
	return YES;
}

- (void)parse:(NSURL *)url application:(UIApplication *)application {
    
    //结果处理
    AlixPayResult* result = [self handleOpenURL:url];
    [[HRPaymentManager shareInstant] cliectPaymentResult:result];
    
//	if (result)
//    {
//		
//		if (result.statusCode == 9000)
//        {
//			/*
//			 *用公钥验证签名 严格验证请使用result.resultString与result.signString验签
//			 */
//            
//            //交易成功
//            //            NSString* key = @"签约帐户后获取到的支付宝公钥";
//            //			id<DataVerifier> verifier;
//            //            verifier = CreateRSADataVerifier(key);
//            //
//            //			if ([verifier verifyString:result.resultString withSign:result.signString])
//            //            {
//            //                //验证签名成功，交易结果无篡改
//            //			}
//            
//        }
//        else
//        {
//            //交易失败
//        }
//    }
//    else
//    {
//        //失败
//    }
    
    
}

- (AlixPayResult *)resultFromURL:(NSURL *)url {
	NSString * query = [[url query] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
	return [[AlixPayResult alloc] initWithString:query];
}

- (AlixPayResult *)handleOpenURL:(NSURL *)url {
	AlixPayResult * result = nil;
	
	if (url != nil && [[url host] compare:@"safepay"] == 0) {
		result = [self resultFromURL:url];
	}
    
	return result;
}


#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (UIViewController *)topViewController
{
    UIViewController *topVC = nil;
    UINavigationController *navVC = (UINavigationController *)self.window.rootViewController;
    while (navVC.presentedViewController != nil) {
        navVC = (UINavigationController *)navVC.presentedViewController;
    }
    topVC = navVC.topViewController;
    while ([topVC isKindOfClass:[UINavigationController class]] || [topVC isKindOfClass:[UITabBarController class]]) {
        if ([topVC isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tabBarVC = (UITabBarController *)topVC;
            topVC = [tabBarVC.viewControllers objectAtIndex:0];
        } else {
            UINavigationController *navVC = (UINavigationController *)topVC;
            topVC = navVC.topViewController;
        }
    }
    
    return topVC;
}

- (void)showUserLoginCompletion:(void (^)(void))completion
{
    UIStoryboard *storyboard=[UIStoryboard storyboardWithName:STORYBOARDNAME_LOGIN bundle:nil];
    UIViewController *viewC = storyboard.instantiateInitialViewController ;
    [HRCommonData shareCommonData].loginCompleteBlock = ^(BOOL isSucceed, NSString *message) {
        if (isSucceed) {
            if (completion) {
                completion();
            };
        }
    };
    NavigationViewController *navVC = [[NavigationViewController alloc] initWithRootViewController:viewC];
    [[self topViewController] presentViewController:navVC animated:YES completion:^{
        
    }];
    
}

@end
